package com.bwhx.eruler.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.bwhx.eruler.bean.OfflineOrder;
import com.bwhx.eruler.bean.Order;
import com.bwhx.eruler.bean.Page;
import com.bwhx.eruler.bean.Ruler;
import com.bwhx.eruler.bean.Staff;
import com.bwhx.eruler.service.OrderService;
import com.bwhx.eruler.service.RulerService;
import com.bwhx.eruler.service.StaffService;
import com.bwhx.eruler.util.DateUtils;
/**
 * 微信订单管理
 * @author Cuilitang
 *
 */

@Controller
public class OrderController extends BaseController {
	
	@Autowired
	OrderService orderService;
	@Autowired
	StaffService staffService;
	@Autowired
	RulerService rulerService;
	
	@ResponseBody
	@RequestMapping(value = "/page.orderList.ashx")
	 public Map orderList(Integer page,Integer rows,Order o) {
		//每页的开始记录
        int start = (page-1)*rows;
        Page p = new Page(start,rows,o);
		Map map = new HashMap();
		try{
			List<Order> list = orderService.list(p);
			Integer count = orderService.count(o);
			log.info(list);
			log.info(count);
			
			map.put("total",count );//total键 存放总记录数，必须的  
			map.put("rows",list);//rows键 存放每页记录 list 
			
			List<Staff> staffList = staffService.listAll();
			HashMap<Integer,String> staffMap = new HashMap<>();
			for (Staff staff : staffList) {
				staffMap.put(staff.getsId(), staff.getsName());
			}
			Integer doneUserId ;
			Integer importUserId ;
			
			for (Order order : list) {
				doneUserId = order.getoDUserId();
				importUserId = order.getoIUserId();
				if (null!=doneUserId&&staffMap.containsKey(doneUserId)) {
					order.setoDUserName(staffMap.get(doneUserId));
				}
				
				if (null!=importUserId&&staffMap.containsKey(importUserId)) {
					order.setoIUserName(staffMap.get(importUserId));
				}
				
			}
			
		}catch(Exception e){
			log.error(getTrace(e));
			map.put("meg", "失败！");
			map.put("status", "0");
		}
		
	    return map;  
	  }
	
	/**
	 * weixin导出的xls表，实际上格式是html的 
	 * POI无法解析，改用jsoup解析
	 * FileTypeId识别文件格式
	 * @param upload
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "/page.uploadxls.ashx")
	 public String uploadxls(HttpSession session,@RequestParam MultipartFile upload) throws IOException {
		ArrayList<Order> orders = new ArrayList<Order>();
		String fileName = ((Staff)session.getAttribute("staff")).getsName()+DateUtils.getStrTime(System.currentTimeMillis()/1000);
		String filePath=session.getServletContext().getRealPath("/WEB-INF/upload");
		//SaveFileFromInputStream(upload.getInputStream(),filePath,fileName);
		upload.transferTo(new File(filePath,fileName));
		File file = new File(filePath,fileName);
		Document doc = Jsoup.parse(file, "UTF-8");
		Elements trs = doc.select("table").select("tr");
		for (int i = 1; i < trs.size(); i++) {
			Elements tds = trs.get(i).select("td");
			Order order = new Order();
			
			order.setoDealTime(DateUtils.getTimeStamp(tds.get(0).text()));
			order.setoId(tds.get(1).text().replace(" ", ""));
			order.setoStatus(0); //未发货
			
			order.setoPName(tds.get(3).text());
			order.setoPPrice(new Float(tds.get(5).text()));
			order.setoPNumber(new Integer(tds.get(6).text()));
			order.setoPMoney(new Float(tds.get(7).text()));
			order.setoPExpressage(new Float(tds.get(8).text()));
			order.setoActualMoney(new Float(tds.get(9).text()));
			
			order.setoBNickname(tds.get(10).text());
			order.setoBIsFans(new Boolean(tds.get(11).text()));
			order.setoBName(tds.get(12).text());
			order.setoBPhone(tds.get(13).text());
			order.setoBAddress(tds.get(14).text());
			
			order.setoECompany(tds.get(15).text());
			order.setoECode(tds.get(16).text());
			
			order.setoIUserId(((Staff)session.getAttribute("staff")).getsId());
			order.setoIUserName(((Staff)session.getAttribute("staff")).getsName());
			order.setoIsDone(0);
			order.setoITime(System.currentTimeMillis()/1000);
			//orderService.insert(order); 将逐条插入改为批量插入，防止部分成功，部分不成功
			orders.add(order);
			for (int j = 0; j < tds.size(); j++) {
				String text = tds.get(j).text().replace(" ", "");
				log.info(text);
			}
		}
		orderService.batchInsert(orders);
		
	    return "success";  
	  }

	   
	@RequestMapping(value = "/page.currentorderdetails.ashx")
	 public ModelAndView currentOrderDetails(@RequestParam String oId){
		Order order = orderService.get(oId);
	    return new ModelAndView("/order/currentorderdetails.jsp","order",order);  
	  }
	
	@ResponseBody
	@RequestMapping(value = "/page.processOrder.ashx")
	 public Map<String,String> processOrder(@RequestBody String b,HttpSession session){
		Map<String,String> resultMap = new HashMap<>();
		resultMap.put("status", "1");
		Order order = new Order();
		List<Ruler> rulers = new ArrayList<Ruler>();
		Map<String, String> map = new HashMap<String, String>();	
		
		String[] split = b.split("&");
		String opcode="";
		String opversion="";
		for (String string : split) {
			String[] keyValue = string.split("=");
			map.put(keyValue[0], keyValue[1]);
		}
		
		Integer oPNumber = Integer.parseInt(map.get("oPNumber"));
		String oId = map.get("oId");
		String oECode = map.get("oECode");
		String oECompany = map.get("oECompany");
		order.setoId(oId);
		order.setoECode(oECode);
		order.setoECompany(oECompany);
		order.setoDTime(System.currentTimeMillis()/1000);
		order.setoDUserId(((Staff)session.getAttribute("staff")).getsId());
		order.setoIsDone(1);//已完成
		order.setoDUserName(((Staff)session.getAttribute("staff")).getsName());
		order.setoStatus(1); //已发货
		String oPCode="";
		ArrayList<String> opcodeList = new ArrayList<String>();
		//code和版本列表
		for(int i=1;i<=oPNumber;i++){
			String opc=map.get("opcode_"+i);
			if(opcodeList.contains(opc)){
				resultMap.put("status", "conflict");
				resultMap.put("RSN", opc);
				return resultMap;
			}else{
				opcodeList.add(opc);
			}
			
			Ruler zaiKuRuler = rulerService.findBySn(opc);
			if(null==zaiKuRuler){
				resultMap.put("status", "nonentity");
				resultMap.put("RSN", opc);
				return resultMap;
			}
			opcode=opc+",";
			opversion=map.get("opversion_"+i);
			oPCode+=opcode;
			Ruler ruler = new Ruler();
			ruler.setRsn(opcode.substring(0,opcode.length()-1));
			ruler.setrVersion(Integer.parseInt(opversion));
			ruler.setrSellTime(System.currentTimeMillis()/1000);
			ruler.setrState(1);
			ruler.setrSellerId(15);//微商城
			rulers.add(ruler);
			
			
		}
		
		order.setoPCode(oPCode.substring(0, oPCode.length()-1));
		
		orderService.update(order,rulers);
				
		return resultMap;  
	  }
	
	@ResponseBody
	@RequestMapping(value = "/page.corderdel.ashx")
 public Map<String,String> OfflineOrderDel(@RequestParam String oId){
	Map<String,String> resultMap = new HashMap<String, String>();
	resultMap.put("status", "1");
	orderService.del(oId);

    return resultMap;  
  }
	
}
